import { Translation as OldTranslation } from '../types/translation';
import { Translation, TranslationInfo, TranslationModule } from '../types/translation';
import { ForexDanaClassificationResult } from './ForexDanaClassifier';
import { moduleNameMapping } from '../config/module-names';

// 为了处理多种格式的翻译数据，定义一个通用类型
interface AnyTranslation {
  key?: string;
  file?: string;
  line?: number;
  column?: number;
  context?: string;
  module?: string;
  tags?: string[];
  frequency?: number;
  node_type?: string;
  attribute?: string;
  element?: string;
  isDefined?: boolean;
  translations?: Array<{
    language: string;
    value: string;
    status: 'valid' | 'invalid' | 'missing';
  }>;
  values?: Array<{
    language: string;
    value: string;
    status: 'valid' | 'invalid' | 'missing';
  }>;
}

/**
 * 转换结果接口
 */
export interface ModuleTransformResult {
  rootModule: Translation;
  statistics: {
    totalModules: number;
    totalKeys: number;
    maxDepth: number;
  };
}

/**
 * ForexDana模块转换器
 * 将平铺的Translation数组转换为层次化的TranslationModule结构
 */
export class ForexDanaModuleTransformer {
  /**
   * 将分类结果转换为模块树结构
   * @param classificationResult ForexDana分类结果
   * @returns 模块树结构
   */
  public transform(classificationResult: ForexDanaClassificationResult): ModuleTransformResult {
    // 创建根节点
    const rootModule: Translation = this.createRootModule();
    
    // 创建两个主要分类节点：基础设施和业务功能
    const infrastructureModule = this.createCategoryModule('infrastructure', '基础设施', 1, rootModule.id);
    const businessModule = this.createCategoryModule('business', '业务功能', 1, rootModule.id);
    const unclassifiedModule = this.createCategoryModule('unclassified', '未分类', 1, rootModule.id);
    
    // 添加到根节点
    rootModule.subModules.push(infrastructureModule);
    rootModule.subModules.push(businessModule);
    rootModule.subModules.push(unclassifiedModule);
    
    // 处理基础设施类模块
    this.processInfrastructureModules(infrastructureModule, classificationResult.infrastructureTranslations);
    
    // 处理业务功能类模块
    this.processBusinessModules(businessModule, classificationResult.businessTranslations);
    
    // 处理未分类翻译
    this.processUnclassifiedTranslations(unclassifiedModule, classificationResult.unclassifiedTranslations);
    
    // 计算统计信息
    const statistics = this.calculateStatistics(rootModule);
    
    return {
      rootModule,
      statistics
    };
  }
  
  /**
   * 创建根模块
   */
  private createRootModule(): Translation {
    return {
      id: 'root',
      isKey: false,
      name: 'ForexDana项目',
      type: 'common',
      path: '',
      tags: ['root', 'project'],
      description: 'ForexDana项目翻译资源',
      subModules: [],
      moduleLevel: 0,
      statistics: {
        total: 0,
        covered: 0,
        invalid: 0,
        duplicate: 0,
        coverageRate: 0,
        qualityScore: 0,
        childModules: 0,
        depth: 0
      }
    };
  }
  
  /**
   * 创建分类模块
   */
  private createCategoryModule(id: string, name: string, level: number, parentId: string): Translation {
    return {
      id: `${parentId}.${id}`,
      isKey: false,
      name,
      type: 'common',
      path: id,
      tags: [id],
      description: `${name}类翻译`,
      subModules: [],
      moduleLevel: level,
      statistics: {
        total: 0,
        covered: 0,
        invalid: 0,
        duplicate: 0,
        coverageRate: 0,
        qualityScore: 0,
        childModules: 0,
        depth: 0
      }
    };
  }
  
  /**
   * 处理基础设施类模块
   */
  private processInfrastructureModules(
    parentModule: Translation, 
    infrastructureTranslations: Record<string, OldTranslation[]>
  ): void {
    // 遍历所有基础设施模块
    for (const [moduleName, translations] of Object.entries(infrastructureTranslations)) {
      if (translations.length === 0) continue;
      
      // 获取友好的模块名称
      const friendlyName = this.getFriendlyModuleName('infrastructure', moduleName);
      
      // 创建模块节点
      const moduleNode = this.createSubModule(
        moduleName,
        friendlyName,
        2,
        parentModule.id,
        'tool'
      );
      
      // 转换翻译键
      moduleNode.subModules = translations.map(translation => 
        this.convertToTranslationInfo(translation, moduleNode.id, 3)
      );
      
      // 更新模块统计信息
      moduleNode.statistics = this.calculateModuleStatistics(moduleNode);
      
      // 添加到父模块
      parentModule.subModules.push(moduleNode);
    }
  }
  
  /**
   * 处理业务功能类模块
   */
  private processBusinessModules(
    parentModule: Translation, 
    businessTranslations: Record<string, OldTranslation[]>
  ): void {
    // 遍历所有业务功能模块
    for (const [moduleName, translations] of Object.entries(businessTranslations)) {
      if (translations.length === 0) continue;
      
      // 获取友好的模块名称
      const friendlyName = this.getFriendlyModuleName('business', moduleName);
      
      // 创建模块节点
      const moduleNode = this.createSubModule(
        moduleName,
        friendlyName,
        2,
        parentModule.id,
        'ui'
      );
      
      // 转换翻译键
      moduleNode.subModules = translations.map(translation => 
        this.convertToTranslationInfo(translation, moduleNode.id, 3)
      );
      
      // 更新模块统计信息
      moduleNode.statistics = this.calculateModuleStatistics(moduleNode);
      
      // 添加到父模块
      parentModule.subModules.push(moduleNode);
    }
  }
  
  /**
   * 处理未分类翻译
   */
  private processUnclassifiedTranslations(
    parentModule: Translation, 
    unclassifiedTranslations: OldTranslation[]
  ): void {
    if (unclassifiedTranslations.length === 0) return;
    
    // 创建模块节点
    const moduleNode = this.createSubModule(
      'others',
      '其他未分类',
      2,
      parentModule.id,
      'common'
    );
    
    // 转换翻译键
    moduleNode.subModules = unclassifiedTranslations.map(translation => 
      this.convertToTranslationInfo(translation, moduleNode.id, 3)
    );
    
    // 更新模块统计信息
    moduleNode.statistics = this.calculateModuleStatistics(moduleNode);
    
    // 添加到父模块
    parentModule.subModules.push(moduleNode);
  }
  
  /**
   * 创建子模块
   */
  private createSubModule(
    id: string, 
    name: string, 
    level: number, 
    parentId: string,
    type: 'common' | 'ui' | 'component' | 'tool' | 'service'
  ): Translation {
    return {
      id: `${parentId}.${id}`,
      isKey: false,
      name,
      type,
      path: id,
      tags: [id, type],
      description: `${name}模块翻译`,
      subModules: [],
      moduleLevel: level,
      statistics: {
        total: 0,
        covered: 0,
        invalid: 0,
        duplicate: 0,
        coverageRate: 0,
        qualityScore: 0,
        childModules: 0,
        depth: 0
      }
    };
  }
  
  /**
   * 将Translation转换为TranslationInfo
   */
  private convertToTranslationInfo(
    translation: AnyTranslation, 
    parentId: string,
    level: number
  ): TranslationInfo {
    // 检查translation是否具有values或translations字段
    let translationValues: Array<{
      language: string;
      value: string;
      status: 'valid' | 'invalid' | 'missing';
    }> = [];
    
    if ('values' in translation && Array.isArray(translation.values)) {
      translationValues = translation.values.map(t => ({
        language: t.language,
        value: t.value,
        status: t.status
      }));
    } else if ('translations' in translation && Array.isArray(translation.translations)) {
      translationValues = translation.translations.map(t => ({
        language: t.language,
        value: t.value,
        status: t.status
      }));
    }
      
    return {
      id: `${parentId}.${translation.key || 'unknown'}`,
      isKey: true,
      moduleLevel: level,
      key: translation.key || 'unknown',
      file: translation.file || '',
      line: translation.line || 0,
      column: translation.column || 0,
      context: translation.context || '',
      module: translation.module || '',
      tags: translation.tags || [],
      frequency: translation.frequency || 1,
      node_type: translation.node_type || '',
      attribute: translation.attribute || '',
      element: translation.element || '',
      isDefined: translation.isDefined || false,
      values: translationValues
    };
  }
  
  /**
   * 获取友好的模块名称
   */
  private getFriendlyModuleName(category: 'infrastructure' | 'business', moduleName: string): string {
    const mapping = moduleNameMapping[category];
    return mapping && mapping[moduleName] ? mapping[moduleName] : `${moduleName}模块`;
  }
  
  /**
   * 计算模块统计信息
   */
  private calculateModuleStatistics(module: Translation): {
    total: number;
    covered: number;
    invalid: number;
    duplicate: number;
    coverageRate: number;
    qualityScore: number;
    childModules: number;
    depth: number;
  } {
    // 计算子模块中的翻译键数量
    let total = 0;
    let covered = 0;
    let invalid = 0;
    let duplicate = 0;
    let childModules = 0;
    let maxChildDepth = 0;
    
    // 处理子模块
    for (const subModule of module.subModules) {
      if (!subModule.isKey) {
        // 递归计算子模块统计
        const subStats = (subModule as Translation).statistics;
        total += subStats.total;
        covered += subStats.covered;
        invalid += subStats.invalid;
        duplicate += subStats.duplicate;
        childModules++;
        maxChildDepth = Math.max(maxChildDepth, subStats.depth);
      } else {
        // 处理翻译键
        const translationInfo = subModule as TranslationInfo;
        total++;
        
        // 计算有效翻译数量
        const validCount = translationInfo.values.filter(v => v.status === 'valid').length;
        if (validCount > 0) {
          covered++;
        }
        
        // 判断无效翻译
        const invalidCount = translationInfo.values.filter(v => v.status === 'invalid').length;
        if (invalidCount > 0) {
          invalid++;
        }
        
        // 判断重复 (这里简化处理)
        if (translationInfo.frequency > 1) {
          duplicate++;
        }
      }
    }
    
    // 计算覆盖率
    const coverageRate = total > 0 ? (covered / total) * 100 : 0;
    
    // 计算质量分数 (简单算法)
    const validRate = total > 0 ? (covered - invalid) / total * 100 : 0;
    const uniqueRate = total > 0 ? (total - duplicate) / total * 100 : 100;
    const qualityScore = (validRate * 0.7 + uniqueRate * 0.3);
    
    // 计算深度
    const depth = maxChildDepth + 1;
    
    return {
      total,
      covered,
      invalid,
      duplicate,
      coverageRate,
      qualityScore,
      childModules,
      depth
    };
  }
  
  /**
   * 计算整体统计信息
   */
  private calculateStatistics(rootModule: Translation): {
    totalModules: number;
    totalKeys: number;
    maxDepth: number;
  } {
    // 递归计算所有模块的统计信息
    this.updateModuleStatisticsRecursively(rootModule);
    
    // 计算总模块数
    let totalModules = 0;
    let totalKeys = 0;
    let maxDepth = 0;
    
    // 遍历计算
    const countModules = (module: Translation) => {
      totalModules++;
      maxDepth = Math.max(maxDepth, module.statistics.depth);
      
      for (const subModule of module.subModules) {
        if (!subModule.isKey) {
          countModules(subModule as Translation);
        } else {
          totalKeys++;
        }
      }
    };
    
    countModules(rootModule);
    
    return {
      totalModules,
      totalKeys,
      maxDepth
    };
  }
  
  /**
   * 递归更新模块统计信息
   */
  private updateModuleStatisticsRecursively(module: Translation): void {
    // 先处理所有子模块
    for (const subModule of module.subModules) {
      if (!subModule.isKey) {
        this.updateModuleStatisticsRecursively(subModule as Translation);
      }
    }
    
    // 更新当前模块的统计信息
    module.statistics = this.calculateModuleStatistics(module);
  }
} 